package com.meizhuo.listview;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.meizhuo.listview.DataSaveUtil.ListDataSave;
import com.meizhuo.listview.api.HttpClient;
import com.meizhuo.listview.network.GetContact_Interface;
import com.meizhuo.listview.network_data.recv_data.Contact_body;
import com.meizhuo.listview.network_data.send_data.Register;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;

public class MyFragment1 extends Fragment {

    private  Handler handler ;

    int []arr = new int[]{
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3
    };

   ArrayList<Register> str ;

    HashMap<String,Object> hashMap = new HashMap<>();

    private Context context ;

    public MyFragment1(){ }

    public  MyFragment1(Context context){
        this.context = context;
    }

    private ArrayList<Register> getContact() throws IOException {

        HttpClient<Contact_body> httpClient = HttpClient.getInstance();

        GetContact_Interface request = httpClient.getHttpClient().create(GetContact_Interface.class);

        Call<Contact_body> call = request.getCall(ListDataSave.getInstance(context,"Userdata").getData("user").getId());

        Contact_body data = call.execute().body();

        if(data == null){
            return null ;
        }
        return data.getData();

    }

    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      View  view = inflater.inflate(R.layout.maillistlayout,container,false);
      listView = view.findViewById(R.id.list_view);
      return view;

    }

    @Override
    public void onStart() {
        super.onStart();

        Log.d("a","shxnja");

        // 从后端拉取用户的信息
       Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    str = getContact();

                    System.out.println(str);

                  Message message=handler.obtainMessage();
                  handler.sendMessage(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

       thread.start();

        handler  = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                // 具体的实现方法：
               final List<HashMap<String,Object>> listData = new ArrayList();

                System.out.println("主线程" + str);

                if(ListDataSave.getInstance(context,"data").setDataList("List",str)){
                    System.out.println("用户列表存储成功");
                }

                for(int i =0;i<str.size();i++){
                    HashMap<String,Object> hashMap = new HashMap<>();
                    hashMap.put("pic",str.get(i).getAvatar());
                    hashMap.put("title",str.get(i).getNickname());
                    listData.add(hashMap);
                }

                // 将 hashMap 的 key 组成一个字符串数组
                String[] form = new String[]{"pic","title"};
                // 将 item 布局中的 view 的 id 组成一个数组，要和 form 对应
                int[] to = new int[]{R.id.pic , R.id.title };
                SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),listData,R.layout.maillist,form,to);

                simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {

                    @Override
                    public boolean setViewValue(View view, Object data,
                                                String textRepresentation) {
                        if (view instanceof ImageView) {
                            ImageView iv = (ImageView) view;
                            Glide.with(iv.getContext()).load((String) data).into(iv);
                            return true;
                        }
                        return false;
                    }
                });

                listView.setAdapter(simpleAdapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        //获得选中项的HashMap对象
                        HashMap<String,Object> map= listData.get(arg2);
                        Object title =  map.get("title");

                        Toast.makeText( context,"选择查看"+title+"的详细信息", Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(context, DetailActivity.class);
                        intent.putExtra("Index", arg2);
                        startActivity(intent);
                    }

                });


            }
        };

    }
}
